﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using Urs.Admin.Models.Localization;
using Urs.Data.Domain.Localization;
using Urs.Data.Domain.Configuration;
using Urs.Services.Localization;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Extensions;
using Urs.Framework.Kendoui;
using Urs.Framework.Mvc;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class LocalizationController : BaseAdminController
	{
		#region Fields
		private readonly ILocalizationService _localizationService;
        private readonly IPermissionService _permissionService;
        private readonly AdminAreaSettings _adminAreaSettings;

		#endregion

		#region Constructors

        public LocalizationController(ILocalizationService localizationService,
            IPermissionService permissionService,
            AdminAreaSettings adminAreaSettings)
		{
			this._localizationService = localizationService;
            this._permissionService = permissionService;
            this._adminAreaSettings = adminAreaSettings;
		}

		#endregion 

		#region Resources

        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return HttpUnauthorized();

            var model = new LocalizationListModel();
            return View(model);
		}

		[HttpPost]
        public IActionResult ListJson(LocalizationListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return HttpUnauthorized();
            
            var query = _localizationService.GetAllResourceValues()
                .OrderBy(x => x.Key).AsQueryable();

            if (!string.IsNullOrEmpty(model.SearchName))
                query = query.Where(l => l.Key.ToLowerInvariant().Contains(model.SearchName.ToLowerInvariant()));
            if (!string.IsNullOrEmpty(model.SearchValue))
                query = query.Where(l => l.Value.Value.ToLowerInvariant().Contains(model.SearchValue.ToLowerInvariant()));


            var resources = query.Select(x => new LocalizationModel()
                    {
                        Id = x.Value.Key,
                        Name = x.Key,
                        Value = x.Value.Value,
                    })
                .ToList();

            var list = new ResponseResult
            {
                data = resources,
                count = resources.Count
            };
            return Json(list);
        }

        
        public IActionResult Update(LocalizationModel model, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return HttpUnauthorized();

            if (model.Name != null)
                model.Name = model.Name.Trim();
            if (model.Value != null)
                model.Value = model.Value.Trim();

            if (!ModelState.IsValid)
            {
                return Json(new ResponseResult { msg = ModelState.SerializeErrors() });
            }

            var resource = _localizationService.GetLocaleStringResourceById(model.Id);
            // if the resourceName changed, ensure it isn't being used by another resource
            if (!resource.Name.Equals(model.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                var res = _localizationService.GetLocaleStringResourceByName(model.Name, false);
                if (res != null && res.Id != resource.Id)
                {
                    return Json(new ResponseResult { msg = string.Format(_localizationService.GetResource("Admin.Configuration.Languages.Resources.NameAlreadyExists"), res.Name) });
                }
            }

            resource.Name = model.Name;
            resource.Value = model.Value;
            _localizationService.UpdateLocaleStringResource(resource);

            return new NullJsonResult();
        }

        
        public IActionResult Add(LocalizationModel model, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return HttpUnauthorized();

            if (model.Name != null)
                model.Name = model.Name.Trim();
            if (model.Value != null)
                model.Value = model.Value.Trim();

            if (!ModelState.IsValid)
            {
                return Json(new ResponseResult { msg = ModelState.SerializeErrors() });
            }

            var res = _localizationService.GetLocaleStringResourceByName(model.Name, false);
            if (res == null)
            {
                var resource = new LocaleStringResource {};
                resource.Name = model.Name;
                resource.Value = model.Value;
                _localizationService.InsertLocaleStringResource(resource);
            }
            else
            {
                 return Json(new ResponseResult { msg = string.Format(_localizationService.GetResource("Admin.Configuration.Languages.Resources.NameAlreadyExists"), model.Name)});
            }
            return new NullJsonResult();
        }
        
        
        public IActionResult Delete(int id, PageRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return HttpUnauthorized();

            var resource = _localizationService.GetLocaleStringResourceById(id);
            if (resource == null)
                throw new ArgumentException("No resource found with the specified id");
            _localizationService.DeleteLocaleStringResource(resource);

            return new NullJsonResult();
        }
        public IActionResult Edit()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return HttpUnauthorized();
            var model = new LocalizationModel();
            return View(model);
        }

        #endregion

    }
}
